var templateParams = {
    tableTheads:["任务名称", "执行机/组", "开时时间", "结束时间", "创建人","任务状态", "总用例数", "已执行数", "成功数"
        , "失败数", "测试进度", "操作"],
    btnTools:[
        {
            type:"danger",
            size:"M",
            id:"batch-op",
            iconFont:"&#xe6bf;",
            name:"批量操作"
        }
    ],
    formControls:[]
};

var columnsSetting = [
    {
        "data":null,
        "render":function(data, type, full, meta){
            return checkboxHmtl(data.job_name, data.id, "selectTask");
        }},
    {"data": "id"},
    {
        "data": "job_name",
        "width": "13%"
    },
    {
        "data": null,
        "width": "9%",
        "render": function(data) {
            let name = GLOBAL_UTILS.stringUtils.isNotBlank(data.executor_name) ? data.executor_name : data.executor_group_name;
            return '<span title="' + name + '">' + name + '</span>';
        }
    },
    ellipsisData("start_time"),
    ellipsisData("completed_time"),
    ellipsisData("creator_name"),
    {
        "data": "status",
        "render": function (data) {
            var option = {
                "stopped":{
                    btnStyle:"default",
                    status:"已停止"
                },
                "wait":{
                    btnStyle:"primary",
                    status:"等待执行"
                },
                "completed":{
                    btnStyle:"success",
                    status:"执行完成"
                },
                "running":{
                    btnStyle:"danger",
                    status:"正在执行"
                },
                "stopping": {
                    btnStyle:"warning",
                    status:"正在停止"
                }
            };
            return labelCreate(data, option);
        }
    },
    {
        "data": "case_count"
    },
    {
        "data": "case_executed_count"
    },
    {
        "data": "case_success_count"
    },
    {
        "data": "case_failed_count"
    },
    {
        "data": null,
        "width": 140,
        "render": function(data){
            if (!GLOBAL_UTILS.numberUtils.isNum(data.case_count) || data.case_count == 0) {
                return '';
            }
            let progress = Math.round(data.case_executed_count / data.case_count * 100);
            let style = 'danger';
            if (progress > 0 && progress < 100) {
                style = 'primary';
            } else if (progress >= 100) {
                style = 'success';
            }
            return '<span class="label label-' + style + ' radius">' + progress + '%</span>';
        }
    },
    {
        "data":null,
        "render":function(data, type, full, meta){
            let context = [{
                title:"查看汇总信息",
                markClass:"exec-summary",
                iconFont:"&#xe621;"
            }];

            if (data.status == 'wait') {
                context.push({
                    title:"删除",
                    markClass:"object-del",
                    iconFont:"&#xe6e2;"
                });
                return btnIconTemplate(context);
            }

            if (data.status == 'running' || data.status == 'stopping') {
                context.push(
                    {
                        title:"停止",
                        markClass:"stop-exec",
                        iconFont:"&#xe6e4;"
                    }
                );
            }

            if (data.status == 'completed' || data.status == 'stopped') {
                context.push(
                    {
                        title:"删除",
                        markClass:"object-del",
                        iconFont:"&#xe6e2;"
                    }
                );
                context.push(
                    {
                        title:"查看测试报告",
                        markClass:"view-report",
                        iconFont:"&#xe61e;"
                    }
                );
            }
            return btnIconTemplate(context);
        }
    }];

var eventList = {
    "#batch-op":function(){
        layer.confirm(
            '请选择你需要进行的批量操作:',
            {
                title:'批量操作',
                btn:['删除', '取消'],
                shadeClose:true,
            },function(index){
                layer.close(index);
                batchOp($(".selectTask:checked"), REQUEST_URL.WEB_TEST_TASK.del, "删除", null, "id");
            },function(index){
                layer.close(index);
            });
    },
    ".object-del":function(){
        let data = table.row( $(this).parents('tr') ).data();

        opObj("确认要删除此测试任务吗？", REQUEST_URL.WEB_TEST_TASK.del, {id:data.id}, this, "删除成功!");
    },
    //查看测试报告
    '.view-report':function(){
        let data = table.row( $(this).parents('tr') ).data();

        GLOBAL_UTILS.ajaxUtils.ajaxGet(REQUEST_URL.WEB_TEST_TASK.report_url + data.id, function(data){
            window.open(REQUEST_URL.BASE_URL + data.data);
        });
    },
    //查看测试日志
    '.view-set-log':function(){
        let setId = $(this).attr('data-id');
        let startIndex = 0;
        let setName = $(this).text();
        let intervalId;
        GLOBAL_UTILS.ajaxUtils.ajaxGet(REQUEST_URL.WEB_TEST_TASK.log, function(data){
            let log = parseLog(data.data);
            startIndex += data.data.length;
            layer_show(setName + ' - 测试日志', templates['task-set-log-view']({
                setName:setName,
                setlog: log
            }), null, null, 1, function(layero, index){
                focusDom($('#taskSetLogView'));
                intervalId = setInterval(function(){
                    GLOBAL_UTILS.ajaxUtils.ajaxGet(REQUEST_URL.WEB_TEST_TASK.log, function(data){
                        if (typeof data.data == 'number' && parseInt(data.data) == 0) {
                            clearInterval(intervalId);
                            return;
                        }

                        startIndex += data.data.length;
                        if (data.data.length > 0) {
                            $('#taskSetLogView').append("<br>" + parseLog(data.data));
                            focusDom($('#taskSetLogView'));
                        }
                    }, null, null, {
                        result_set_id:setId, start: startIndex
                    })
                }, 1000);

            }, null, function(){
                if (intervalId != null) {
                    clearInterval(intervalId);
                }
            });
        }, null, null, {result_set_id:setId, start: startIndex}, '正在获取日志内容...');

    },
    '.stop-exec':function(){
        let data = table.row( $(this).parents('tr') ).data();

        layer.confirm('确定要停止该测试任务吗？', {title: '警告', icon: 0}, function(index){
            GLOBAL_UTILS.ajaxUtils.ajaxGet(REQUEST_URL.WEB_TEST_TASK.stop + '&job_id=' + data.id, function(data){
                refreshTable();
                layer.msg('停止成功！', {time: 1600, title: '提示'});
            }, null, null, null, '正在停止中...');

            layer.close(index);
        });
    },
    //查看用例汇总信息
    '.exec-summary':function() {
        let data = table.row( $(this).parents('tr') ).data();

        GLOBAL_UTILS.ajaxUtils.ajaxGet(REQUEST_URL.WEB_TEST_TASK.execSummary + '&job_id=' + data.id, function(d) {
            //计算汇总
            countSummary(d.data);
            let refreshFlag = false;
            let intervalId;

            layer_show(data.job_name + '-汇总信息', templates['task-case_summary']({
                summaryRow: d.data,
                refreshFlag: refreshFlag
            }), null, null, 1, function(layero, index){

                $(layero).delegate('#open-summary-refresh', 'click', function(){
                    if (refreshFlag) {
                        //关闭
                        if (intervalId != null) {
                            clearInterval(intervalId);
                            intervalId = null;
                        }
                        $(this).removeClass('btn-default').addClass('btn-primary').text('开启自动刷新');
                        refreshFlag = false;
                    } else {
                        //开启
                        intervalId = setInterval(function(){
                            GLOBAL_UTILS.ajaxUtils.ajaxGet(REQUEST_URL.WEB_TEST_TASK.execSummary + '&job_id=' + data.id, function(d) {
                                countSummary(d.data);
                                $(layero).find('.layui-layer-content').html(templates['task-case_summary']({
                                    summaryRow: d.data,
                                    refreshFlag: refreshFlag
                                }));
                            });
                        }, 3000);

                        $(this).addClass('btn-default').removeClass('btn-primary').text('关闭自动刷新');
                        refreshFlag = true;
                    }
                });
            }, null, function(){
                if (intervalId != null) {
                    clearInterval(intervalId);
                }
            });
        }, null, null, null, '正在加载中...');
    }
};

var mySetting = {
    eventList:eventList,
    templateCallBack:function(df){
        df.resolve();
    },
    listPage:{
        listUrl:REQUEST_URL.WEB_TEST_TASK.list,
        tableObj:".table-sort",
        columnsSetting:columnsSetting,
        columnsJson:[0, 13],
        dtOtherSetting:{
            serverSide:false
        }
    },
    templateParams:templateParams
};

$(function(){
    publish.renderParams = $.extend(true,publish.renderParams,mySetting);
    publish.init();
});


function countSummary(data){
    //计算汇总
    let summaryRow = {
        testset_name: '汇总',
        executor_group_name: '-',
        case_count: 0,
        case_executed_count: 0,
        case_success_count: 0,
        case_failed_count: 0,
        status: '-'
    };

    $.each(data, function(i, n){
        summaryRow['case_count'] += n.case_count;
        summaryRow['case_executed_count'] += n.case_executed_count;
        summaryRow['case_success_count'] += n.case_success_count;
        summaryRow['case_failed_count'] += n.case_failed_count;
    });

    data.push(summaryRow);
}


function focusDom(dom) {
    dom.append('<input type="text" id="hiddenInput"/>')
    $('#hiddenInput').focus();
    $('#hiddenInput').remove();
}

function parseLog (logs) {
    if (!GLOBAL_UTILS.arrayUtils.isArray(logs) || logs.length < 1) {
        return '';
    }

    let newLogs = [];
    $.each(logs, function(i, n){
        let log = '';
        log = '<span class="label label-secondary radius">' + n.substr(0, 23) + '</span>';
        let ss = n.substr(23).split('#');
        let fontStyle = 'c-green';
        if (ss[0].indexOf("ERROR") > -1) {
            fontStyle = "c-error";
        }
        if (ss[0].indexOf("WARNING") > -1) {
            fontStyle = "c-warning";
        }

        log += '&nbsp;<span class="' + fontStyle + '">' + ss[0] + '</span>';
        log += '&nbsp;#&nbsp;' + ss[1];
        newLogs.push(log);
    });

    return newLogs.join('<br>');
}